<template>
  <div class="staff-container">
    <el-aside width="200px" class="sidebar">
      <el-menu router :default-active="$route.path">
        <el-menu-item index="/staff/meeting">会议室管理</el-menu-item>
        <el-menu-item index="/staff/worklog">工作日志</el-menu-item>
        <el-menu-item index="/staff/order">审核订单</el-menu-item>
    </el-menu>
    </el-aside>

    <div class="main-content">
      <div class="staff-header" style="background: #e3f2fd; padding: 0 1rem; height: 40px; display: flex; align-items: center; justify-content: space-between">
      <h1 style="color: #2c3e50; margin: 0; font-size: 16px">员工后台</h1>
      <div class="user-avatar" @click.stop="toggleDropdown" style="margin-left: auto">
        <el-avatar
          :size="40"
          :icon="User"
          class="avatar-icon"
          style="
            background-color: #409eff;
            color: white;
            border: 2px solid #fff;
            box-shadow: 0 2px 6px rgba(64, 158, 255, 0.3);
          "
        />
        <div v-if="showDropdown" class="dropdown-menu">
          <div class="menu-item" @click="handleProfile">个人信息</div>
          <div class="menu-item" @click="handleLogout">退出登录</div>
        </div>
      </div>
      
    </div>
      <div class="content-area">
        <router-view></router-view>
      </div>
    </div>

    <el-dialog v-model="dialogVisible" title="个人信息" width="30%">
      <el-form
        :model="formData"
        :rules="formRules"
        ref="formRef"
        label-width="80px"
      >
        <el-form-item label="用户名">
          <el-input v-model="formData.username" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="formData.password" type="password" />
        </el-form-item>
        <el-form-item label="真实姓名">
          <el-input v-model="formData.realName" />
        </el-form-item>
        <el-form-item
          label="手机号"
          prop="phone"
          :rules="[
            {
              required: true,
              pattern: /^1[3-9]\d{9}$/,
              message: '请输入有效的11位手机号码',
            },
          ]"
        >
          <el-input v-model="formData.phone" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>
  
  <script setup>
import { ref, onMounted, onUnmounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import axios from "axios";
import { User } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { Menu as IconMenu, Document, Checked } from "@element-plus/icons-vue";

const $route = useRoute();
const $router = useRouter();
const socket = ref(null);
const sid = ref(Math.random().toString().substr(2,10));

const showDropdown = ref(false);

// 页面加载时检查当前路由，如果不是会议室管理则跳转
if (!['/staff/meeting', '/staff/worklog', '/staff/order-review'].includes($route.path)) {
  $router.push('/staff/meeting');
}

const toggleDropdown = () => {
  showDropdown.value = !showDropdown.value;
};

const dialogVisible = ref(false);
const formRef = ref(null);

const formRules = {
  username: [{ required: true, message: "用户名不能为空" }],
  realName: [{ required: true, message: "真实姓名不能为空" }],
  phone: [
    { required: true, message: "手机号不能为空" },
    { pattern: /^1[3-9]\d{9}$/, message: "请输入有效的11位手机号码" },
  ],
};

const formData = ref({
  username: "",
  password: "",
  realName: "",
  phone: "",
  company: "",
});

const handleProfile = async () => {
  try {
    const response = await axios.get("/api/staff/account");
    formData.value = response.data.data;
    formData.value.password = null;

    dialogVisible.value = true;
  } catch (error) {
    console.error("获取个人信息失败:", error);
    ElMessage.error("获取信息失败");
  }
};

const handleSave = async () => {
  try {
    await formRef.value.validate((valid) => {
      if (!valid) {
        ElMessage.error("请完善表单信息");
        return;
      }
    });
    await axios.post("/api/staff/account/update", formData.value, {
      headers: {
        "Content-Type": "application/json",
      },
    });
    ElMessage.success("保存成功");
    dialogVisible.value = false;
  } catch (error) {
    if (!error.response) {
      ElMessage.error("表单验证失败");
    }
    console.error("保存失败:", error);
  }
};

// WebSocket消息处理
const handleWsMessage = (event) => {
  try {
    const { customer, content } = JSON.parse(event.data);
    ElMessage({
      type: 'info',
      message: `来自${customer}的提醒：${content}`,
      duration: 5000,
      showClose: true
    });
  } catch (e) {
    console.error('消息解析失败:', e);
  }
};

// 初始化WebSocket连接
onMounted(() => {
  socket.value = new WebSocket(`ws://${location.host}/tws/${sid.value}`);
  
  socket.value.onmessage = handleWsMessage;
  socket.value.onerror = (e) => {
    ElMessage.error('WebSocket连接异常');
    console.error('WebSocket error:', e);
  };
  socket.value.onclose = () => {
    console.log('WebSocket连接关闭');
  };
});

// 清理WebSocket连接
onUnmounted(() => {
  if (socket.value && socket.value.readyState === WebSocket.OPEN) {
    socket.value.close();
  }
});

const handleLogout = async () => {
  try {
    await axios.get("/api/staff/account/loginout");
    window.location.href = "/staff-login";
  } catch (error) {
    console.error("退出登录失败:", error);
  }
};
</script>
  
  <style scoped>
.staff-container {
  display: flex;
  flex-direction: row;
  min-height: 100vh;
}

.sidebar {
  width: 200px;
  height: 100vh;
  box-shadow: 2px 0 6px rgba(0,0,0,0.1);
}

.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.content-area {
  flex: 1;
  padding: 20px;
  overflow: auto;
}

.staff-header {
  height: 40px;
  display: flex;
  align-items: center;
  padding: 0 1rem;
}

.el-menu {
  border-left: none;
}

.el-menu-item {
  height: 56px;
  display: flex;
  align-items: center;
}
  

.user-avatar {
  position: relative;
  cursor: pointer;
}

.user-avatar img {
  width: 40px;
  height: 40px;
  border-radius: 50%;
}

.dropdown-menu {
  position: absolute;
  right: 0;
  top: 55px;
  background: white;
  border: 1px solid #ebeef5;
  border-radius: 6px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  min-width: 120px;
  z-index: 1000;
}

.menu-item {
  padding: 10px 16px;
  cursor: pointer;
  font-size: 14px;
  color: #606266;
  transition: all 0.3s;
}

.menu-item:hover {
  background-color: #f5f7fa;
  color: #409eff;
}

h1 {
  color: #2c3e50;
  margin-bottom: 1.5rem;
}
</style>